package com.lzy.canal.component.result.mysql;

import com.alibaba.otter.canal.protocol.CanalEntry;
import com.lzy.canal.component.result.BaseConsumerResultData;
import com.lzy.canal.enums.ConsumerRestTypeEnum;

import java.util.Map;

/**
 * dml 语句处理结果抽象类
 *
 */
public abstract class AbstractConsumerDmlRestData implements BaseConsumerResultData {
    private final String ID_KEY;
    private final String IS_DELETED_KEY;

    protected AbstractConsumerDmlRestData(String idKey, String isDeletedKey) {
        ID_KEY = idKey;
        IS_DELETED_KEY = isDeletedKey;
    }

    /**
     * 获取源数据
     *
     * @return
     */
    @Override
    public abstract Map<String, Object> getResource();

    /**
     * 获取id
     *
     * @return
     */
    public String getId() {
        return String.valueOf(getResource().get(ID_KEY));
    }

    /**
     * 返回 ConsumerRestTypeEnum
     *
     * @return
     */
    public abstract ConsumerRestTypeEnum getType();



    /**
     * 获取dml操作类型
     *
     * @return
     */
    ConsumerRestTypeEnum getConsumerRestTypeEnum() {
        if (CanalEntry.EventType.INSERT.equals(getEventType())) {
            return ConsumerRestTypeEnum.INSERT;
        }
        if (CanalEntry.EventType.DELETE.equals(getEventType())) {
            return ConsumerRestTypeEnum.DELETED;
        }
        if (isDeleted()) {
            return ConsumerRestTypeEnum.DELETED;
        }
        return ConsumerRestTypeEnum.UPDATE;

    }


    private Boolean isDeleted() {
        Map<String, Object> resource = getResource();
        if (resource == null) {
            return false;
        }
        return "1".equals(String.valueOf(resource.get(IS_DELETED_KEY)));
    }


}
